<template>
  <div class="flex flex-col h-full">
    <a-card>
      <div class="flex justify-between items-center">
        <a-button type="primary" class="mr-4" @click="router.go(-1)"> 返回 </a-button>
        <a-descriptions class="mt-3 ml-8" :column="6">
          <a-descriptions-item label="单号" class="w-1/6"> {{ formState?.applyDh || '-' }}</a-descriptions-item>
          <a-descriptions-item label="申领日期" class="w-1/6"> {{ formState?.applyTime || '-' }}</a-descriptions-item>
          <a-descriptions-item label="申领仓库" class="w-1/6"> {{ formState?.storeName || '-' }}</a-descriptions-item>
          <a-descriptions-item label="制单人" class="w-1/6"> {{ formState?.applyByName }}</a-descriptions-item>
          <a-descriptions-item label="制单时间" class="w-1/6"> {{ formState?.createTime || '-' }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-card>
    <a-card class="mt-2 flex-1">
      <BaseTable
        :data-source="tableData"
        :loading="loading"
        max-fill
        :extra-height="64"
        column-code="000315"
        :pagination="pagination"
        :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'drugName'">
            <EditCell title="药品名称" class="ml-2">
              <MedicineInfo :value="{ mc: record?.drugName, gg: record?.gg, cj: record?.cj }" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'confirmQty'">
            <EditCell title="申领数量">
              <a-input v-model:value="record.confirmQty" v-input:format.0 placeholder="请输入" class="text-right" @blur="editRow(record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'memo'">
            <span v-if="record.memo">{{ record.memo }}</span>
            <span v-else>-</span>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <BaseButton confirm-text="确认删除此明细?" type="text" danger size="small" :disabled="record.status === '1'" @click="onDel(record)">
              删除
            </BaseButton>
          </template>
        </template>
        <template #footer>
          <div class="text-center sticky bottom-0">
            <a-button type="primary" :disabled="tableData.length === 0" @click="saveNewRows()"> 保存 </a-button>
          </div>
        </template>
      </BaseTable>
    </a-card>
  </div>
</template>

<script setup>
import { ref, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import BaseTable from '@/components/BaseTable'
import { post } from '@/utils/request'
import EditCell from '@/components/EditCell'

const route = useRoute()
const router = useRouter()
const formState = ref({})
const getMainData = async () => {
  const { data, code, msg } = await post('/drugStorage/consume/getKcApplyEntity', {
    applyDh: route.query.dh || ''
  })
  if (code !== 0) return message.error(msg || '获取数据失败')
  formState.value = data
  getData()
}

const onDel = async (record) => {
  if (record.id) {
    const { code, msg } = await post('/drugStorage/consume/delKcApplyDetail', { id: record.id })
    if (code !== 0) return message.error(msg || '删除失败')
    message.success(msg)
    tableData.value = tableData.value.filter((item) => item.key !== record.key)
    getData()
  } else {
    tableData.value = tableData.value.filter((item) => item.key !== record.key)
  }
}

const editRow = (row) => {
  if (row.isNew) return
  if (row.confirmQty > 0) {
    if (row.confirmQty > row.qty) {
      return message.error('确认数量不可大于申领数量')
    } else {
      fetchSave(row, 'obj')
    }
  } else {
    return message.error('确认数量需大于0')
  }
}
const fetchSave = async (row, type) => {
  if (type === 'obj') {
    const rows = {
      applyDh: formState.value.applyDh,
      ...row
    }
    const { code, msg } = await post('/drugStorage/consume/doSaveKcApplyDetail', rows)
    if (code !== 0) return message.error(msg || '操作失败')
  } else {
    const { code, msg } = await post('/drugStorage/consume/doSaveKcApplyDetailList', row)
    if (code !== 0) return message.error(msg || '操作失败')
  }
  message.destroy()
  message.success(row.isNew ? '新增成功' : '修改成功')
  getData()
}
//添加行
// const addRow = async () => {
//   const key = `row-${tableData.value.length}`
//   const addRow = { key, isNew: true, applyDh: formState.value.applyDh }
//   tableData.value.push(addRow)
// }

const { loading, tableData, getData, pagination } = useTable({
  url: '/drugStorage/consume/getKcApplyDetailList',
  immediate: false,
  formatParams: () => {
    return {
      applyDh: formState.value.applyDh,
      ckbh: formState.value.storeCode
    }
  }
})

const saveNewRows = async () => {
  const newRow = tableData.value.filter((item) => item.isNew)
  const flag = newRow.filter((item) => !item.qty)
  if (flag && flag.length > 0) {
    message.destroy()
    message.error('请填写完整信息')
  } else {
    fetchSave(newRow, 'arr')
  }
}

watchEffect(() => {
  if (route.query?.dh) {
    getMainData()
  }
})
</script>
<style lang="less" scoped>
:deep(.ant-table-row-expand-icon) {
  display: none;
}
</style>
